import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/common/routers/router_names.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/utils/util_toast.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/page/main.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';

class EditProfilePage extends StatefulWidget {
  const EditProfilePage({super.key});

  @override
  State<EditProfilePage> createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  late TextEditingController nicknameController;
  late TextEditingController signatureController;
  late TextEditingController birthdayController;
  late TextEditingController cityController;
  User? user;
  File? _avatarFile;

  @override
  void initState() {
    super.initState();
    final bloc = context.read<AwakBloc>();
    user = bloc.userRepository.currentUser;
    nicknameController = TextEditingController(text: user?.nickname ?? '');
    signatureController = TextEditingController(text: user?.signature ?? '');
    birthdayController = TextEditingController(text: user?.birthday ?? '');
    cityController = TextEditingController(text: user?.city ?? '');
  }

  @override
  void dispose() {
    nicknameController.dispose();
    signatureController.dispose();
    birthdayController.dispose();
    cityController.dispose();
    super.dispose();
  }

  Future<void> _pickAvatar() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: const AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
      ),
    );
    if (result != null && result.isNotEmpty) {
      final file = await result.first.file;
      if (file != null) {
        setState(() {
          _avatarFile = file;
        });
      }
    }
  }

  void _save() async {
    if (user == null) return;
    String? avatarPath = user?.avatar;
    if (_avatarFile != null) {
      avatarPath = _avatarFile!.path;
    }
    final updatedUser = user!.copyWith(
      nickname: nicknameController.text,
      signature: signatureController.text,
      birthday: birthdayController.text,
      city: cityController.text,
      avatar: avatarPath,
    );
    await context.read<AwakBloc>().userRepository.update(updatedUser);
    context.read<AwakBloc>().userRepository.currentUser = updatedUser;
    // 触发 Bloc 状态刷新
    context.read<AwakBloc>().add(LoginEvent(updatedUser.username, updatedUser.password));
    // 切换 tab 到 Profile
    context.read<TabIndexCubit>().setIndex(3);
    if (mounted) {
      AwakToast.showCustomToast(context, 'save success!');
      Future.delayed(const Duration(milliseconds: 2300), () {
        Beamer.of(context).beamBack();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          onPressed: () {
            context.read<TabIndexCubit>().setIndex(3);
            Beamer.of(context).beamBack();
          },
          icon: Icon(AwakSvg.back, size: 20.w),
        ),
        title: Text('EDIT PROFILE', style: AwakText.titleStyle),
      ),
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AwakImages.editBg),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: 20.h),
          Stack(
            children: [
              GestureDetector(
                onTap: _pickAvatar,
                child: Container(
                  margin: EdgeInsets.only(top: 110.h),
                  width: 120.w,
                  height: 120.h,
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.black, width: 4.w),
                    image: DecorationImage(
                      image: _avatarFile != null
                          ? FileImage(_avatarFile!)
                          : (user?.avatar != null && user!.avatar!.isNotEmpty
                              ? AssetImage(user!.avatar!)
                              : AssetImage(AwakImages.avatar)) as ImageProvider,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: 45.w,
                right: 45.w,
                child: Icon(AwakSvg.camera, size: 28.w, color: Colors.white),
              ),
            ],
          ),
          SizedBox(height: 50.h),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 10.h),
            decoration: BoxDecoration(color: Colors.transparent),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Nickname',
                  style: AwakText.body14Style.copyWith(
                    color: Colors.black.withOpacity(0.5),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                TextField(controller: nicknameController),
                SizedBox(height: 30.h),
                Text(
                  'Personalized Signature',
                  style: AwakText.body14Style.copyWith(
                    color: Colors.black.withOpacity(0.5),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                TextField(controller: signatureController),
                SizedBox(height: 30.h),
                Text(
                  'Birthday',
                  style: AwakText.body14Style.copyWith(
                    color: Colors.black.withOpacity(0.5),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                TextField(controller: birthdayController),
                SizedBox(height: 30.h),
                Text(
                  'City',
                  style: AwakText.body14Style.copyWith(
                    color: Colors.black.withOpacity(0.5),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                TextField(controller: cityController),
              ],
            ),
          ),
          Spacer(),
          // Collect按钮
          GestureDetector(
            onTap: () {
              Beamer.of(context).beamToNamed(RouterNames.collectProfile);
            },
            child: Container(
              width: double.infinity,
              margin: EdgeInsets.symmetric(horizontal: 32.w),
              padding: EdgeInsets.symmetric(vertical: 14.h),
              decoration: BoxDecoration(
                color: Color(0xFFFFF45C),
                borderRadius: BorderRadius.circular(8.r),
                border: Border.all(color: Colors.black, width: 2.w),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(AwakSvg.collect, size: 20.w, color: Colors.black),
                  SizedBox(width: 8.w),
                  Text(
                    'My Collect',
                    textAlign: TextAlign.center,
                    style: AwakText.body16Style.copyWith(
                      fontWeight: FontWeight.w500,
                      color: Colors.black,
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 16.h),
          // Save按钮
          GestureDetector(
            onTap: _save,
            child: Container(
              width: double.infinity,
              margin: EdgeInsets.symmetric(horizontal: 32.w),
              padding: EdgeInsets.symmetric(vertical: 14.h),
              decoration: BoxDecoration(
                color: Color(0xFFB6F558),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Text(
                'Save',
                textAlign: TextAlign.center,
                style: AwakText.body16Style.copyWith(
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
          SizedBox(height: 40.h),
        ],
      ),
      ),
    );
  }
}
